<!--心理测评管理-->
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import startNetwork from '@/utils/http.js'
// 导入工具方法
import { getFileUrl, uploadFile  } from '@/utils/fileHelper';



//定义localStorage
let userInfo = ref({})
let role = ref('')
// 表格数据
const tableData = ref([
  {
    index: 1,
    type_id: '1',
    type_name: '1',
    type_count: '1',
    imgurl: '1'
  }
])

// 搜索表单
const searchForm = reactive({
  text: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 6
})

// 对话框相关
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const form = reactive({
  type_id: '',
  type_name: '',
  imgurl: ''
})
const currentStudent = ref({})
const formRef = ref(null)
const currentEditId = ref(null)

// 表单验证规则
const rules = reactive({
  type_name: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
  imgurl: [{ required: true, message: '请选择上传图片', trigger: 'change' }]
})

// 选中行
const selectedRows = ref([])

// 加载状态
const loading = ref(false)

// 表格引用
const tableRef = ref(null)

// 搜索
const handleSearch = () => {
  loading.value = true
  pagination.currentPage = 1
  pagination.pageSize = 5
  fetchStudents()
  // 实际项目中这里应该调用API获取搜索结果
  // 从数据库中获取数据,get请求
// 模拟API请求延迟
  setTimeout(() => {
    loading.value = false
    ElMessage.success('搜索完成')
  }, 500)
}

// 重置
const handleReSet = () => {
  loading.value = true
  searchForm.text = ''
  pagination.currentPage = 1
  pagination.pageSize = 5
  fetchStudents()
  setTimeout(() => {
    loading.value = false
    ElMessage.success('重置完成')
  }, 500)
}

// 添加学生
const handleAdd = () => {
  dialogTitle.value = '添加题目类型'
  currentEditId.value = null
  resetForm()
  dialogVisible.value = true
  // 增加学生

}

// 编辑学生
const handleEdit = (row) => {
  dialogTitle.value = '编辑学生'
  currentEditId.value = row.type_id
  Object.assign(form, row)
  dialogVisible.value = true
}

// 查看详情
const handleDetail = (row) => {
  currentStudent.value = { ...row }
  detailDialogVisible.value = true
}

// 删除学生
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该学生吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // tableData.value = tableData.value.filter(item => item.studentId !== row.studentId)
    // 删除学生
    let res = await startNetwork({
      url: "/api/assessment-types/delete",
      method: "delete",
      params: {
        oldTypeId: row.type_id
      },
      headers: {
        // 不设置请求头
        'Content-Type': 'none'
      }
    })
    if (res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchStudents()
    } else if (res.data.code === 300) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条数据')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const ids = selectedRows.value.map(item => item.type_id)
    console.log("ids:==========")
    console.log(ids)

    // 调用API批量删
    let res = await startNetwork({
      url: "/api/assessment-types/deleteBatch",
      method: "delete",
      data: ids,
      headers: {
        // json
        'Content-Type': 'application/json'
      }
    })
    if (res.data.code === 200) {
      ElMessage.success('删除成功')
      fetchStudents()
    }else{
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 排序变化
const handleSortChange = ({ column, prop, order }) => {
  // 实际项目中这里应该调用API重新获取排序后的数据
  // 这里简单实现本地排序
  console.log(column)
  if (order) {
    tableData.value.sort((a, b) => {
      if (order === 'ascending') {
        return a[prop] > b[prop] ? 1 : -1
      } else {
        return a[prop] < b[prop] ? 1 : -1
      }
    })
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1 // 改变每页大小时回到第一页
  fetchStudents()
  // 这里应该重新获取数据
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchStudents()
  // 这里应该重新获取数据
}

// 提交添加和编辑表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (currentEditId.value) {
        // 编辑逻辑
        const index = tableData.value.findIndex(item => item.type_id === currentEditId.value)
        if (index !== -1) {
          tableData.value[index] = {...form}
        }
        // 提交编辑
        let res = await startNetwork({
          url: "/api/assessment-types/update",
          // 用json传输
          method: "put",
          data: {
            oldTypeId: currentEditId.value,
            typeId: form.type_id,
            typeName: form.type_name,
            imgurl: form.imgurl,
          },
          headers: {
            'Content-Type': 'application/json'
          }
        })
        console.log(res)
        if (res.data.code === 200) {
          ElMessage.success('编辑成功')
        } else if (res.data.code === 300) {
          ElMessage.error('编辑失败')
        }
      } else {
        let res = await startNetwork({
          url: "/api/assessment-types/add",
          // 用json传输
          method: "post",
          data: {
            typeId: null,
            typeName: form.type_name,
            imgurl: form.imgurl,
          },
          headers: {
            'Content-Type': 'application/json'
          }
        })

        if (res.data.code === 200) {
          // 刷新表格数据
          fetchStudents()
          ElMessage.success('添加成功')
        }else if (res.data.code === 500){
          ElMessage.error('添加失败,该学号已存在')
        }else {
          ElMessage.error('添加失败,请联系管理员')
        }
      }
      dialogVisible.value = false
    }
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    type_id: '',
    type_name: '',
    imgurl: ''
  })
}

// 获取学生信息
async function fetchStudents() {
//   初始化参数
  const params = {
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
    // 搜索条件（如果有）
    ...(searchForm.text && { text: searchForm.text }),

  }

  let res = await startNetwork({
    url: "/api/assessment-types/list",
    params: params
  });
  console.log("获取学生信息============")
  if (res.data.code === 200) {
    console.log(res.data.data)
    // 映射数据到表格
    tableData.value = res.data.data.list.map((item, index) => ({
      index: (pagination.currentPage - 1) * pagination.pageSize + index + 1,
      type_id: item.typeId,
      type_name: item.typeName,
      type_count: item.typeCount,
      imgurl: item.imgurl
    }))
    console.log("映射后的表格数据============")
    console.log(tableData.value)

    // 更新分页信息
    pagination.total = res.data.data.total
  }
}

onMounted(() => {
  fetchStudents()
  // 从 localStorage 获取用户信息
  const storedUserInfo = localStorage.getItem('userInfo');
  console.log("进入了 onMounted")
  console.log(storedUserInfo)
  if (storedUserInfo) {
    // 解析为对象
    userInfo.value = JSON.parse(storedUserInfo);
    console.log("这是 userInfo:");
    console.log(userInfo.value);
    role.value = userInfo.value.role;
    console.log("这是 role:");
    console.log(role.value);
  }
});
async function handleAvatarChange(e){
  console.log(e.raw)
  let res = await uploadFile(e.raw)
  console.log("上传文件的结果:")
  console.log(res)
  console.log("imgurl:")
  console.log(form.imgurl)
  form.imgurl = res.data.data
  console.log("更新后的imgurl:")
  console.log(form.imgurl)
}

</script>

<template>
  <div class="">
    <!--<h2>题目类型111管理</h2>-->
    <div class="student-management-container">
      <!-- 搜索和操作区域 -->
      <div class="operation-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="题目类型名称">
            <el-input v-model="searchForm.text" placeholder="请输入题目类型名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button type="primary" @click="handleReSet">重置</el-button>
          </el-form-item>
        </el-form>

        <div class="action-buttons">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>添加类型名称
          </el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
            <el-icon><Delete /></el-icon>批量删除
          </el-button>
        </div>
      </div>

      <!-- 学生信息表格 -->
      <el-table
        ref="tableRef"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        v-loading="loading"
        :header-cell-style="{ backgroundColor: '#f5f7fa' }"
      >
        <el-table-column type="selection" width="48" fixed="left" />
        <el-table-column type="selection" width="48" fixed="left" />
        <!-- 修改后的索引列 -->
        <el-table-column
          label="序号"
          width="80"
          fixed="left"
        >
          <template #default="scope">
            {{ (pagination.currentPage - 1) * pagination.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="type_id"
          label="类型id"
          width="100"
          sortable
          :sort-orders="['ascending', 'descending']"
        />
        <el-table-column
          prop="type_name"
          label="类型名称"
          width=""
          sortable
          :sort-orders="['ascending', 'descending']"
        />
        <el-table-column
          prop="type_count"
          label="该类型的问卷数量"
          width="180"
          sortable
          :sort-orders="['ascending', 'descending']"
        />
        <el-table-column
          prop="imgurl"
          label="类型图片"
          width="150"
          sortable
          :sort-orders="['ascending', 'descending']"
        >
          <template #default="scope">
            <el-image
              :src="getFileUrl(scope.row.imgurl)"
              style="width:100px;"
            />
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="220"
          fixed="right"
        >
          <template #default="scope">
            <el-button-group class="action-buttons">
              <el-button
                size="small"
                type="primary"
                @click="handleDetail(scope.row)"
              >
                详情
              </el-button>
              <el-button
                size="small"
                type="warning"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="题目类型详情"
        width="50%"
      >
        <el-descriptions :column="2" border>
          <el-descriptions-item label="类型id">{{ currentStudent.type_id }}</el-descriptions-item>
          <el-descriptions-item label="类型名">{{ currentStudent.type_name }}</el-descriptions-item>
          <el-descriptions-item label="套题数量">{{ currentStudent.type_count }}</el-descriptions-item>
          <el-descriptions-item label="图片展示">
            <el-image
              :src="getFileUrl(currentStudent.imgurl)"
              style="width:150px;"
            />
          </el-descriptions-item>
        </el-descriptions>
        <template #footer>
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>

      <!-- 添加/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
        :close-on-click-modal="false"
      >
        <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
          <el-form-item v-if="currentEditId" label="类型id" prop="type_id">
            <el-input v-model="form.type_id" />
          </el-form-item>
          <el-form-item label="类型名称" prop="type_name">
            <el-input v-model="form.type_name" />
          </el-form-item>
          <el-form-item label="该类型的图片" prop="imgurl">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :on-change="handleAvatarChange"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.imgurl" :src="getFileUrl(form.imgurl)" class="avatar" width="150px"/>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>

        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
.page-content {
  text-align: center;
  color: #666;
}

.page-content h2 {
  color: #1e3a8a;
  margin-bottom: 10px;
}
.student-management-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.operation-area {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 操作按钮组样式 */
.action-buttons {
  display: flex;
  gap: 6px;
}

.action-buttons .el-button {
  padding: 6px 8px;
  min-width: 60px;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
}

.el-table .el-table__cell {
  padding: 8px 0;
}

.el-table th.el-table__cell > .cell {
  white-space: nowrap;
  font-weight: bold;
}

/* 详情对话框样式 */
.el-descriptions {
  margin-top: 20px;
}

.el-descriptions-item__label {
  width: 100px;
  font-weight: bold;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
